<template>
  <div class="video-player">
    <div :id="id"></div>
  </div>
</template>
<script setup name="EsayPlayer">
import { ElMessage } from 'element-plus'
import { uuid } from '@/utils/utils.js'
import { onBeforeUnmount } from 'vue'
import { videoKeepLive, realPlayUrl, recordPlayUrl } from '@/api/camera/cameraPlayer.js'

const props = defineProps({
  playerData: {
    type: Object,
    default: () => {
      return {}
    }
  },
  playerType: {
    type: String,
    default: () => {
      return ''
    }
  }
})
const id = ref(uuid())
const videoItem = ref({})
const interval = ref(null)
const player = ref(null)

watch(
  () => props.playerData.channelId,
  (newChannelId) => {
    if (newChannelId) {
      if (props.playerType === 'real') {
        getRealPlayUrl()
      } else {
        getRecordPlayUrl()
      }
    }
  },
  { immediate: true }
)

// 实时视频接口
const getRealPlayUrl = () => {
  const { channelId, manufacturer } = props.playerData
  realPlayUrl({ channelId, manufacturer }).then((res) => {
    videoItem.value = res.data
    initPlayer()
  })
}

// 历史视频接口
const getRecordPlayUrl = () => {
  const { channelId, manufacturer, beginTime, endTime, streamType, location } = props.playerData
  recordPlayUrl({ channelId, manufacturer, beginTime, endTime, streamType, location }).then((res) => {
    if (res.code === 200) {
      videoItem.value = res.data
      initPlayer()
    } else {
      ElMessage({ type: 'info', message: res.msg })
    }
  })
}

// 初始化播放器
const initPlayer = (url) => {
  if (player.value) player.value.stop()
  nextTick(() => {
    /* eslint-disable */
    player.value = new WasmPlayer(null, id.value, callbackFun, { Height: true, fluent: true, HideKbs: true })
    player.value.play(videoItem.value.uri, 1)
  })
}

// 保活
const keepLive = () => {
  if (interval.value) clearInterval(interval.value)
  interval.value = setInterval(() => {
    videoKeepLive({ sessionId: videoItem.value.sessionId, channelId, manufacturer }).then((res) => {
      console.log(res)
    })
  }, 30000)
}

const callbackFun = (e) => {
  if (e === 'play') {
    keepLive()
  }
  if (e === 'stop') {
    clearInterval(interval.value)
  }
}

onBeforeUnmount(() => {
  if (player.value) {
    player.value.stop()
    player.value.destroy()
    clearInterval(interval.value)
  }
})
</script>

<style lang="scss">
.video-player {
  width: 100%;
  height: 100%;
  background-color: #0a0d16;
  position: relative;
  font-size: 0.12rem;

  .iconqingxiLOGO:before {
    // 去除logo
    content: '';
  }
}
</style>
